﻿using GenericHtml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using WLFramework.Data.Linq;
using WLFramework.Json;
using WLFramework.Mapping;
using WLFramework.Web;

namespace SampleSite.admin.ajax
{
    /// <summary>
    /// setAppRoles 的摘要说明
    /// </summary>
    public class setAppRoles : AjaxHttpHandler
    {
        public class JsonData
        {
            public int a_id { get; set; }
            public List<int> r_ids { get; set; }
        }

        public override void OnProcessRequest(HttpContext context)
        {
            string data = context.GetValueByName<string>("data");
            if (data != null && data.Trim().Length != 0)
            {
                throw new Exception("输入参数错误!");
            }

            var input = JSON.Instance.ToObject<JsonData>(data);
            
            using (CommandHelper db = new CommandHelper(CommandMethod.Write))
            {
                db.Context.BeginTransaction();
                if (db.Context.sys_Applications.Where(k => k.A_ID == input.a_id).Count() != 1)
                    throw new Exception("输入参数错误!");

                db.Context.sys_RoleApplication.Where(k => k.A_ID == input.a_id)
                          .Delete();

                if (input.r_ids != null && input.r_ids.Count != 0)
                {
                    List<sys_RoleApplication> rows = new List<sys_RoleApplication>();
                    foreach (var i in input.r_ids)
                    {
                        rows.Add(new sys_RoleApplication()
                        {
                            A_ID = input.a_id,
                            R_ID = i,
                            A_State = 1
                        });
                    }

                    db.Context.InsertBatch(rows);
                }

                db.Context.CommitTransaction();
            }

            context.Response.Write(JSON.Instance.ToJSON(JSONResult.Success));
        }
    }
}